package DFS_BFS;

/**
 * @PackageName: DFS_BFS
 * @ClassName: LeetCode1302
 * @Author: chen jinxu
 * @Date: 2022/8/17 23:45
 * @Description: //层数最深叶子节点的和
 * 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和 。
 * 输入：root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 * 输出：15
 * 输入：root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
 * 输出：19
 */
public class LeetCode1302 {
    public static void main(String[] args) {
        System.out.println(deepestLeavesSum(new TreeNode(1, new TreeNode(2, new TreeNode(4, new TreeNode(7), null), new TreeNode(5)), new TreeNode(3, null, new TreeNode(6, null, new TreeNode(8))))));
    }
    static int maxLevel = -1;
    static int sum = 0;
    public static int deepestLeavesSum(TreeNode root) {
        dfs(root, 0);
        return sum;
    }

    public static void dfs(TreeNode node, int level) {
        if (node == null) {
            return;
        }
        if (level > maxLevel) {
            maxLevel = level;
            sum = node.val;
        } else if (level == maxLevel) {
            sum += node.val;
        }
        dfs(node.left, ++level);
        dfs(node.right, ++level);
    }


    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {

        }

        TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
